package cn.rongdao.jrkabao.ui.login;

import android.content.Context;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.ImageView;

import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRCollection;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;

import butterknife.BindView;
import cn.mifengkong.appcommon.smsverify.SMSVerify;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseAutoFinishActivity;
import cn.rongdao.jrkabao.model.login.CheckVerifyInfoModel;
import cn.rongdao.jrkabao.model.login.GetCodeModel;
import cn.rongdao.jrkabao.model.login.InviteCodeNecessaryModel;
import cn.rongdao.jrkabao.ui.login.uicomponent.LoginBottomUIComponent;
import cn.rongdao.jrkabao.ui.login.uicomponent.LoginInputUIComponent;
import cn.rongdao.jrkabao.util.CommonUtil;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function4;

/**
 * Created by jack on 2018/4/20
 */

public class RegisterActivity extends BaseAutoFinishActivity {

    public static final String IS_FORGET_PWD = "is_forget_pwd";
    public static final String IS_SET_PWD = "is_set_pwd";

    public static void start(Context context, boolean isForgetPwd, boolean isSetPwd) {
        Bundle bundle = new Bundle();
        bundle.putBoolean(IS_FORGET_PWD, isForgetPwd);
        bundle.putBoolean(IS_SET_PWD, isSetPwd);
        FRStartActivity.start(context, RegisterActivity.class, bundle);
    }

    public static void start(Context context) {
        start(context, false, false);
    }

    public static void startFromForgetPwd(Context context) {
        start(context, true, false);
    }

    public static void startFromSetPwd(Context context) {
        start(context, false, true);
    }

    @BindView(R.id.ar_titlebar)
    TitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.ar_iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.ar_phone_input)
    LoginInputUIComponent phoneInput;
    @BindView(R.id.ar_verify_input)
    LoginInputUIComponent verifyInput;
    @BindView(R.id.ar_invite_input)
    LoginInputUIComponent inviteInput;
    @BindView(R.id.ar_login_bottom)
    LoginBottomUIComponent loginBottomUIComponent;

    private CompositeDisposable compositeDisposable;
    private boolean isSendMsg;
    private SMSVerify smsVerify;

    private boolean isForgetPwd;
    private boolean isSetPwd;
    private boolean mustInviteCode;

    @Override
    protected int layoutRes() {
        return R.layout.activity_register;
    }

    @Override
    protected void initView() {
        super.initView();
        isForgetPwd = getIntent().getBooleanExtra(IS_FORGET_PWD, false);
        isSetPwd = getIntent().getBooleanExtra(IS_SET_PWD, false);
        initTitleBar();
        compositeDisposable = new CompositeDisposable();
        smsVerify = new SMSVerify(60);

        initInput();
        initListener();
    }

    private void initListener() {
        verifyInput.setSendMsgOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage();
            }
        });
        loginBottomUIComponent.setOnLoginClickListener("下一步", new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                checkVerifyInfo();
            }
        });
        smsVerify.setOnSMSTimeListener(new SMSVerify.OnSMSTimeListener() {
            @Override
            public void onReceiveSMS(String second) {
                isSendMsg = true;
                verifyInput.setSendMsgContent(FRCollection.appendAsString(second, "s重新获取", ""));
                verifyInput.setSendMsgEnable(false);
            }

            @Override
            public void onNotReceiveSMS() {
                isSendMsg = false;
                verifyInput.setSendMsgContent("重新发送");
                verifyInput.setSendMsgEnable(true);
            }
        });
    }

    private void sendMessage() {
        GetCodeModel.getInstance().execute(phoneInput.getInputContent(), isForgetPwd ? "3" : isSetPwd ? "2" : "1", new FRBaseObserver<String>(this, "正在获取验证码，请稍候...") {
            @Override
            protected void onBaseNext(String data) {
                smsVerify.startCountDown();
            }
        });
    }

    private void checkVerifyInfo() {
        if (CommonUtil.checkPhone(phoneInput.getInputContent()) && checkVerify()) {
            CheckVerifyInfoModel.getInstance()
                    .addParams("phone", phoneInput.getInputContent())
                    .addParams("validate_code", verifyInput.getInputContent())
                    .addParams("invitation_code", inviteInput.getInputContent())
                    .execute(new FRBaseObserver<String>(this) {
                        @Override
                        protected void onBaseNext(String data) {
                            if (isForgetPwd) {
                                ForgetPasswordActivity.startFromForgetPwd(thisActivity(), phoneInput.getInputContent(), verifyInput.getInputContent());
                            } else if (isSetPwd) {
                                ForgetPasswordActivity.start(thisActivity(), phoneInput.getInputContent(), verifyInput.getInputContent());
                            } else {
                                ForgetPasswordActivity.startFromRegister(thisActivity(), phoneInput.getInputContent(), verifyInput.getInputContent(), inviteInput.getInputContent());
                            }
                        }
                    });
        }
    }

    private boolean checkVerify() {
        if (verifyInput.getInputContent().length() < 4) {
            FRToast.showToastSafe("请输入4位验证码");
            return false;
        }
        return true;
    }

    private void initInput() {
        phoneInput.setInputMaxLength(11);
        phoneInput.setInputType(InputType.TYPE_CLASS_PHONE);
        phoneInput.setHint("请输入手机号");
        phoneInput.initDelete();

        verifyInput.setInputMaxLength(4);
        verifyInput.setInputType(InputType.TYPE_CLASS_NUMBER);
        verifyInput.setHint("请输入验证码");

        if (isForgetPwd || isSetPwd) {
            inviteInput.setVisibility(View.GONE);
        } else {
            inviteInput.setInputMaxLength(6);
            getMustInviteCode();
        }
        compositeDisposable.add(Observable.combineLatest(phoneInput.getInputObservable(), verifyInput.getInputObservable(), inviteInput.getInputObservable(), loginBottomUIComponent.getCheckBoxObservable(), new Function4<CharSequence, CharSequence, CharSequence, Boolean, Boolean>() {
            @Override
            public Boolean apply(CharSequence phoneSequence, CharSequence verifySequence, CharSequence inviteSequence, Boolean aBoolean) throws Exception {
                if (mustInviteCode) {
                    return !FRString.isEmpty(FRString.valueOf(phoneSequence), FRString.valueOf(verifySequence), FRString.valueOf(inviteSequence)) && aBoolean;
                }
                return !FRString.isEmpty(FRString.valueOf(phoneSequence), FRString.valueOf(verifySequence)) && aBoolean;
            }
        }).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                loginBottomUIComponent.setLoginBtnEnable(aBoolean);
            }
        }));

        compositeDisposable.add(phoneInput.getInputObservable().subscribe(new Consumer<CharSequence>() {
            @Override
            public void accept(CharSequence charSequence) throws Exception {
                if (!isSendMsg) {
                    verifyInput.setSendMsgEnable(!FRString.isEmpty(FRString.valueOf(charSequence)) && charSequence.length() == 11);
                }
            }
        }));
    }

    private void getMustInviteCode() {
        InviteCodeNecessaryModel.getInstance().execute(new FRBaseObserver<String>(this) {
            @Override
            protected void onBaseNext(String data) {
                mustInviteCode = CommonUtil.isStatusSuccess(data);
                inviteInput.setVisibility(View.VISIBLE);
                inviteInput.setHint(mustInviteCode ? "请输入邀请码(必填)" : "请输入邀请码(选填)");
            }
        });
    }

    private void initTitleBar() {
        titleBarUIComponent.initTitleBlack(isForgetPwd ? "忘记密码" : isSetPwd ? "设置密码" : "注册");
        ivAvatar.setVisibility((!isForgetPwd && !isSetPwd) ? View.VISIBLE : View.GONE);
        titleBarUIComponent.initLeft(R.drawable.icon_close, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected boolean useBlackStatusBarOnWhite() {
        return true;
    }

    @Override
    public void onDestroy() {
        if (null != smsVerify) {
            smsVerify.gcTimer();
        }
        phoneInput.onDestroy();
        verifyInput.onDestroy();
        loginBottomUIComponent.onDestroy();
        if (null != compositeDisposable) {
            compositeDisposable.dispose();
            compositeDisposable = null;
        }
        super.onDestroy();
    }
}